<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1400px">
    <el-form ref="formRef" :model="formData" class="mt-12px">
      <el-form-item label="数据标准">
        <el-select
          v-model="templateId"
          clearable
          filterable
          placeholder="请选择数据标准"
          @change="templateChange"
          :disabled="props.type !== 'outside'"
        >
          <el-option
            v-for="(template, templateIndex) in templateList"
            :key="templateIndex"
            :label="template.dataStandardName"
            :value="template.id"
          />
        </el-select>
      </el-form-item>

      <el-table :data="formData.list">
        <el-table-column
          v-if="dataType !== 'file'"
          :prop="dataType"
          label="名称"
          show-overflow-tooltip
        />
        <el-table-column
          min-width="150px"
          label="名称"
          show-overflow-tooltip
          fixed="left"
          v-if="dataType == 'file'"
        >
          <template #default="scope">
            <ns-input v-model="formData.list[scope.$index].fileName" />
          </template>
        </el-table-column>
        <el-table-column label="文件类型" min-width="100px" v-if="dataType == 'file'">
          <template #default="scope">
            <ns-input v-model="formData.list[scope.$index].fileType" />
          </template>
        </el-table-column>
        <el-table-column label="文件大小" min-width="100px" v-if="dataType == 'file'">
          <template #default="scope">
            <ns-input v-model="formData.list[scope.$index].fileSize" />
          </template>
        </el-table-column>
        <el-table-column
          v-for="(column, columnIndex) in columnList"
          :key="columnIndex"
          :label="column.name ? column.name : `字段${columnIndex + 1}`"
        >
          <template #default="scope">
            <el-form-item
              :prop="`list[${scope.$index}][institutionFiled${column.index}]`"
              :rules="[{ required: column.required == '1', message: `${column.name}不能为空` }]"
            >
              <div style="width: 100%">
                <el-cascader
                  :filter-method="sysFilterMethod"
                  @change="(e) => classChange(e, column.index, scope.$index)"
                  placeholder="请选择分类"
                  v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                  :options="classOptions"
                  :props="{
                    value: 'field1',
                    label: 'field1_name',
                    checkStrictly: true,
                    expandTrigger: 'hover',
                    emitPath: false
                  }"
                  v-if="column.index == '1'"
                  filterable
                />
                <el-select
                  v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                  placeholder="请选择"
                  style="width: 100%"
                  v-else-if="column.index == '2'"
                  @change="institutionFiledChange(column.index, scope.$index)"
                >
                  <el-option
                    v-for="item in cascaderAllOptions?.[scope.$index]?.[`field${column.index - 1}`]"
                    :key="item[`field${column.index}`]"
                    :value="item[`field${column.index}`]"
                    :label="item[`field${column.index}_name`]"
                  />
                </el-select>
                <el-select
                  v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                  placeholder="请选择"
                  clearable
                  allow-create
                  filterable
                  v-else-if="column.index == '3' && dropdownData"
                  @change="
                    () => {
                      institutionFiledChange(column.index, scope.$index)
                      timeFiledChange(scope.$index)
                    }
                  "
                >
                  <el-option
                    v-for="item in cascaderAllOptions?.[scope.$index]?.[`field${column.index - 1}`]"
                    :key="item[`field${column.index}`]"
                    :value="item[`field${column.index}`]"
                    :label="item[`field${column.index}`]"
                  />
                </el-select>
                <ns-input
                  v-else-if="column.fillingMethod == '输入框'"
                  v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                  clearable
                  placeholder="请输入"
                />
                <el-select
                  v-else-if="column.fillingMethod == '选择器' && dropdownData"
                  clearable
                  v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                  placeholder="请选择"
                  @change="institutionFiledChange(column.index, scope.$index)"
                >
                  <el-option
                    v-for="item in cascaderAllOptions?.[scope.$index]?.[`field${column.index - 1}`]"
                    :key="item[`field${column.index}`]"
                    :value="item[`field${column.index}`]"
                    :label="item[`field${column.index}`]"
                  />
                </el-select>
                <el-date-picker
                  v-else-if="column.fillingMethod == '日期'"
                  v-model="formData.list[scope.$index][`institutionFiled${column.index}`]"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </div>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(extend, extendIndex) in extendList"
          :key="extendIndex"
          :label="extend.name ? extend.name : `字段${extendIndex + 1}`"
        >
          <template #default="scope">
            <el-form-item
              :prop="`list[${scope.$index}][field${extend.index}]`"
              :rules="[{ required: extend.required == '1', message: `${extend.name}不能为空` }]"
            >
              <div style="width: 100%">
                <el-select
                  v-model="formData.list[scope.$index][`field${extend.index}`]"
                  placeholder="请选择"
                  v-if="extend.index == '3'"
                >
                  <el-option
                    v-for="item in levelList"
                    :key="item.levelCode"
                    :label="item.levelName"
                    :value="item.levelCode"
                  />
                </el-select>
                <ns-input
                  v-else-if="extend.fillingMethod == '输入框'"
                  v-model="formData.list[scope.$index][`field${extend.index}`]"
                  clearable
                  placeholder="请输入"
                />
                <el-select
                  v-else-if="extend.fillingMethod == '选择器'"
                  clearable
                  v-model="formData.list[scope.$index][`field${extend.index}`]"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(option, optionIndex) in extend.presetContentMap"
                    :key="optionIndex"
                    :label="option"
                    :value="option"
                  />
                </el-select>
                <el-date-picker
                  v-else-if="extend.fillingMethod == '日期'"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  v-model="formData.list[scope.$index][`field${extend.index}`]"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  @change="dateChange(scope.$index, extend.index)"
                />
              </div>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <el-button
        type="primary"
        @click="submitForm('2')"
        v-if="btnStatus === 'showAudit' && assetFrom !== 'importAsset'"
        >保存并提交审核</el-button
      >
      <el-button
        type="primary"
        @click="submitImportForm"
        v-if="btnStatus === 'showAudit' && assetFrom === 'importAsset'"
        >保存并提交审核</el-button
      >
      <el-button type="primary" @click="submitForm('3')" v-if="btnStatus === 'showConfirm'"
        >保存并提交确认</el-button
      >
      <el-button type="primary" @click="submitForm('1')" v-if="assetFrom !== 'importAsset'"
        >保 存</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { getAssetByLevel, assetUpdateLevelList } from '@/api/assetDetail'
import { assetMessagePassUpdateAndAuditBatch, getDataBasePassList } from '@/api/assetPass/index'
import { fileAuditBatch } from '@/api/assetList/index'
import * as assuranceApi from '@/api/dataStandards/assurance/index'
import { infoPage } from '@/api/dataStandards/info/index'
import { sysFilterMethod } from '@/utils/selectFilter'
import {
  valueConfGetByValue,
  valueConfFieldValue,
  valueConfGetByValueTree
} from '@/api/dataStandards/assuranceValue/index'
import { levelPage } from '@/api/strategyManage/level/index'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { getProcessDefinitionOne } from '@/api/bpm/definition'
import dayjs from 'dayjs'
import useCascader from '@/hooks/event/useCascader'
const route = useRoute()
const flattenDownList = ref([])
const message = useMessage() // 消息弹窗
const cascaderAllOptions = ref([])
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const dataType = ref() //弹窗的数据类型
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const classOptions = ref([])
const btnStatus = ref() //弹窗按钮状态 showAudit：展示保存并提交审核 showConfirm：展示保存并提交确认
const assetFrom = ref()
const props = defineProps({
  type: {
    type: String,
    default: ''
  }
})

const formData = ref({
  list: []
})
const formRef = ref() // 表单 Ref

const templateList = ref([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({
    page: 1,
    pageSize: 999,
    status: '1',
    type: dataType.value == 'file' ? 0 : 1
  })
  templateList.value = data
}

// 分类修改
let classChange = (e, scopeIndex, index) => {}

// 数据选择修改后，控制后面字段的修改
let institutionFiledChange = () => {}
// 更新字段

const dateChange = (scopeIndex, index) => {
  if (index == '1') {
    timeFiledChange(scopeIndex)
  }
}

const timeFiledChange = (scopeIndex) => {
  let convertedTime = convertTimeFormat(formData.value.list[scopeIndex].institutionFiled3)
  if (!convertedTime) {
    let currentClass = allLevelList.value.find(
      (item) => item.levelCode == formData.value.list[scopeIndex].institutionFiled2
    )
    console.log(
      formData.value.list[scopeIndex].institutionFiled2,
      allLevelList.value,
      'currentClass'
    )
    convertedTime =
      convertTimeFormat(currentClass?.deadlineTimeNum + currentClass?.deadlineTimeUnit) || {}
  }
  formData.value.list[scopeIndex].field2 = dayjs(formData.value.list[scopeIndex].field1)
    .add(Number(convertedTime.num), convertedTime.unit)
    .format('YYYY-MM-DD HH:mm:ss')
}
// 时间格式转换
function convertTimeFormat(timeString) {
  if (!timeString) {
    return
  }
  // 匹配数字和单位部分的正则表达式
  const regex = /(\d+)\s*([^0-9\s]+)/
  // 匹配结果
  const match = timeString.match(regex)
  const unitMap = new Map([
    ['年', 'year'],
    ['月', 'month'],
    ['天', 'day'],
    ['日', 'day']
  ])

  // 如果匹配成功，则返回 num 和 unit 对象
  if (match) {
    //单位不对则退出
    if (!unitMap.get(match[2])) {
      return false
    }
    return {
      num: parseInt(match[1]),
      unit: unitMap.get(match[2])
    }
  } else {
    // 如果匹配失败，返回空对象
    return false
  }
}

const templateId = ref()
const getTableList = async (ids) => {
  dialogVisible.value = true
  const Api = assetFrom.value == 'importAsset' ? getDataBasePassList : getAssetByLevel
  const { data } = await Api({
    ids
  })
  for (let i = 0; i < data.length; i++) {
    tempLevelList.value.push({ data: [] })
  }
  dataType.value = data[0].dataType
  // TODO 判断所有数据的模板是不是同一个 不是就不能批量分类分级
  templateId.value = getSameTemplate(data)

  // 第三批修改内容，批量修改可以修改模版
  // if (data && data.length === 1 && !data[0].template) {
  //   message.warning('所选资产未绑定数据保护模板！')
  //   dialogVisible.value = false
  //   return
  // }
  getTemplateList()
  if (templateId.value) {
    // 如果有共同模版
    // TODO 同一个数据标准就调取该模板下面的制度配置和扩展字段配置
    formData.value.list = data.map((item) => {
      return {
        ...item
        // 等级下拉回显
      }
    })
    formData.value.list = formData.value.list.map((item) => {
      return {
        ...item,
        institutionFiled1: item.handClassification || item.classification || '',
        institutionFiled2: item.institutionFiled2
          ? item.institutionFiled2
          : String(item.level) != 'null' && String(item.level) != 'undefined'
            ? String(item.level)
            : '',
        template: templateId.value
      }
    })
    console.log(formData.value.list, 2)
    await getClassLevelList()
    getColumn()
    getInfoList()
    await getDownList()
    formData.value.list.map((item, idx) => {
      classChange(item.institutionFiled1, 1, idx)
    })

    // getLevelList()
  } else {
    formData.value.list = data
    // message.warning('所选资产的数据标准不同！')
    // dialogVisible.value = false
  }
}

// 判断数组对象中的template都一样
function getSameTemplate(array) {
  // 如果数组为空，则返回标识
  if (array.length === 0) {
    return false
  }
  // 获取第一个对象的 template
  const template = array[0].template
  // 遍历数组，检查每个对象的 template 是否都与第一个对象相同
  for (const item of array) {
    if (item.template !== template) {
      return '' // 如果有一个 template 不同，则返回标识
    }
  }
  // 如果遍历完所有对象，都没有发现不同的 template，则返回 template 值
  return template
}

async function templateChange() {
  await getClassLevelList()
  getColumn()
  getInfoList()
  await getDownList()
  formData.value.list.map((item) => {
    Object.keys(item).forEach((key) => {
      if (key.startsWith('institutionFiled') || key.startsWith('field')) {
        item[key] = ''
      }
    })
    return {
      ...item,
      template: templateId.value
      // 等级下拉回显
    }
  })
  formData.value.list.map((item, idx) => {
    classChange(item.institutionFiled1, 1, idx)
  })
}

const columnList = ref([])
const allLevelList = ref([])
// 获取表格列（制度信息）
const getColumn = async () => {
  const data = await assuranceApi.assurancePage({
    dataStandardId: templateId.value,
    display: 1,
    page: 1,
    pageSize: 20
  })
  if (data.length > 0) {
    columnList.value = data
  } else {
    columnList.value = []
  }
}
const extendList = ref([])
// 获取模板扩展字段列表
const getInfoList = async () => {
  const data = await infoPage({
    page: 1,
    pageSize: 20,
    dataStandardId: templateId.value, //固定一个模板先用于测试
    display: '1'
  })
  extendList.value = data.map((item) => {
    return {
      ...item,
      presetContentMap: item.presetContent ? JSON.parse(item.presetContent) : []
    }
  })
  getLevelList()
}

/** 查询非分类分级的下拉列表 */
const downLists = ref([])
const dropdownData = ref()
const getDownList = async () => {
  const data = await valueConfGetByValue({
    dataStandardId: templateId.value
  })
  let treeData = await valueConfGetByValueTree({
    dataStandardId: templateId.value
  })
  let { inFiledChange, typeChange, byValuetreeData, byValueData, cascaderSelectOptions } =
    useCascader({
      treeData,
      data,
      listValue: ref(formData.value.list),
      tempLevelList: tempLevelList.value
    })

  institutionFiledChange = inFiledChange
  classChange = typeChange
  cascaderAllOptions.value = cascaderSelectOptions.value

  if (data.length > 0) {
    downLists.value = byValueData
    flattenDownList.value = byValuetreeData
    dropdownData.value = convertToDropdownData(downLists.value)
  } else {
    downLists.value = data
    flattenDownList.value = []
    classOptions.value = setClassOptionsMap(flattenDownList.value)
  }
}
const convertToDropdownData = (data) => {
  const dropdownData = {}
  Object.keys(data[0]).forEach((key) => {
    if (key.startsWith('field')) {
      if (key.startsWith('field3'))
        dropdownData[key] = Array.from(
          new Set(data.map((item) => item[key]).filter((value) => value !== ''))
        )
    }
  })
  return dropdownData
}

// 获取内容配置中分类分级的下拉
const tempClassList = ref([])
const tempLevelList = ref([])
const getClassLevelList = async () => {
  tempClassList.value = await valueConfFieldValue({
    dataStandardId: templateId.value,
    type: '1'
  })
  const levelOptions = await valueConfFieldValue({
    dataStandardId: templateId.value,
    type: '2'
  })
  let levelOptionsData = levelOptions.map((ite) => {
    return {
      ...ite,
      disabled: false
    }
  })

  tempLevelList.value = levelOptionsData
}

// 获取等级下拉列表
const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  const deadLineConf = extendList.value.find((item) => item.index === 3)
  if (deadLineConf && deadLineConf.presetContent && deadLineConf.presetContent !== '[]') {
    const presetCodes = JSON.parse(deadLineConf.presetContent)
    const arr = data.filter((item) => presetCodes.includes(item.levelCode))
    levelList.value = arr.map((ite) => {
      ite.levelCode = ite.levelCode + ''
      return ite
    })
  } else {
    levelList.value = data.map((ite) => {
      ite.levelCode = ite.levelCode + ''
      return ite
    })
  }
  allLevelList.value = data
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
// isAudit ：1 普通保存 2:保存并提交审核 3:保存并提交确认
const submitForm = async (isAudit) => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const submitData = formData.value.list.map((item) => {
      return {
        ...item,
        handClassification: item.institutionFiled1,
        handLevel: item.institutionFiled2,
        secretDeadline: item.institutionFiled3,
        secretStartTime: item.field1,
        deadlineTime: item.field2,
        deadlineLevel: item.field3,
        submitStatus: isAudit == '3' ? '1' : item.submitStatus,
        template: templateId.value
      }
    })
    const data = await assetUpdateLevelList(submitData)
    if (data) {
      if (isAudit === '1' || isAudit === '3') {
        message.success('操作成功')
        dialogVisible.value = false
        // 发送操作成功的事件
        emit('success')
      } else if (isAudit === '2') {
        const submitData = formData.value.list.map((item) => {
          return {
            assetId: item.id,
            assetType: item.dataType,
            deptId: item.deptId,
            sysId: item.sysId
          }
        })
        const res = await fileAuditBatch(submitData)
        if (res) {
          message.success('操作成功')
          dialogVisible.value = false
          // 发送操作成功的事件
          emit('success')
        }
      }
    }
  } finally {
    formLoading.value = false
  }
}

const submitImportForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const submitData: any = []
    for (let i = 0; i < formData.value.list.length; i++) {
      const item = formData.value.list[i]
      const processList = await getProcessDefinitionOne({
        assetId: item.id,
        assetType: item.dataType === 'file' ? 'file' : 'db',
        deptId: item.deptId,
        sysId: item.sysId
      })
      let processDefinitionKey
      if (processList.length) {
        const processId = processList[0].id
        const firstColonIndex = processId.indexOf(':')
        processDefinitionKey = processId.slice(0, firstColonIndex)
      }

      submitData.push({
        ...item,
        handClassification: item.institutionFiled1,
        handLevel: item.institutionFiled2,
        secretDeadline: item.institutionFiled3,
        secretStartTime: item.field1,
        deadlineTime: item.field2,
        deadlineLevel: item.field3,
        processDefinitionKey: processDefinitionKey,
        auditType:
          item.dataType === 'column'
            ? 'passColumn'
            : item.dataType === 'table'
              ? 'passTable'
              : 'passFile'
      })
    }
    const data = await assetMessagePassUpdateAndAuditBatch(submitData)
    if (data) {
      message.success('操作成功')
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    }
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    list: []
  }
  formRef.value?.resetFields()
}

/** 打开弹窗 */
const open = async (ids, type, from) => {
  dialogTitle.value = '批量修改'
  btnStatus.value = type
  assetFrom.value = from
  resetForm()
  getTableList(ids)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const setClassOptionsMap = (data) => {
  return data.map((item) => {
    item.field1_name = tempClassList.value.find((fitem) => fitem.key == item.field1)?.value
    item.disabled = item.isSelect == '0'
    item.children.length && setClassOptionsMap(item.children)
    return item
  })
}
watch(
  () => [tempClassList.value, downLists.value],
  () => {
    if (downLists.value?.length > 0 && tempClassList.value?.length > 0) {
      classOptions.value = setClassOptionsMap(flattenDownList.value)
    }
  }
)
</script>

<style scoped lang="scss">
:deep(.el-form-item--default) {
  margin-bottom: 0 !important;
}
</style>
